<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\controller;

use think\facade\Db;
use app\BaseController;
use app\wework\model\Helper;
use app\wework\model\BaseModel;
use app\wework\model\user\staff\StaffModel;
use think\facade\Log;
use app\wework\model\QyWechatApi;
use app\wework\model\CallbackModel;
use think\facade\Event;
use think\facade\Cache;
include "../extend/Qywxcypto/WXBizMsgCrypt.php";


/**
 * 外部联系人回调
 */
class CustomerCallback extends BaseController
{
	public $wid;
	public $config = [];

	/**
	 * 外部联系人回调入口
	 */
	public function index(){
		if(isset($_GET['echostr'])){
			//接受验证数据 
		  	$sVerifyMsgSig = $_GET['msg_signature'];
			$sVerifyTimeStamp = $_GET['timestamp']; 
			$sVerifyNonce = $_GET['nonce'];
			$sVerifyEchoStr = $_GET['echostr'];
			$configList = BaseModel::getAll('kt_wework_config');
			foreach($configList as $config){
				$encodingAesKey = $config['customer_aes'];
				$token = $config['customer_token'];
				$corpId = $config['corp_id']; 
				$wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
				// 需要返回的明文
				$sEchoStr = ""; 
				$errCode = $wxcpt->VerifyURL($sVerifyMsgSig, $sVerifyTimeStamp, $sVerifyNonce, $sVerifyEchoStr, $sEchoStr);
				if($errCode == 0){
					 echo $sEchoStr;
					 exit();
				}
			}
		}else{
			//搜集参数
			$sReqMsgSig = $_GET['msg_signature'];
			$sReqTimeStamp = $_GET['timestamp'];
			$sReqNonce = $_GET['nonce'];
			//获取xml冰去除特殊字符
			$sReqData = preg_replace("/[\n\s]/", '', file_get_contents('php://input'));
			//解密
			$this->config = $config = BaseModel::find('kt_wework_config',['corp_id'=>xmlToArray($sReqData)['ToUserName']]);
			$encodingAesKey = $config['customer_aes'];
			$token = $config['customer_token'];
			$corpId = $config['corp_id']; 
			$wxcpt = new \WXBizMsgCrypt($token, $encodingAesKey, $corpId);
			$sMsg = "";  // 解析之后的明文
			$errCode = $wxcpt->DecryptMsg($sReqMsgSig, $sReqTimeStamp, $sReqNonce, $sReqData, $sMsg);
			if(!Cache::get($_GET["msg_signature"])){
			    Cache::set($_GET["msg_signature"],$_GET["msg_signature"],60);
    			if ($errCode == 0) {
    				$arr = xmlToArray($sMsg);
    				if($arr['Event'] == 'change_external_contact'){
    					if($arr['ChangeType'] == 'add_external_contact'){
    						$this->addExternalContact($arr);
    						Event::trigger('CustomerCallback',$arr);
    					}elseif($arr['ChangeType'] == 'edit_external_contact'){
    						$this->edit_external_contact($arr);
    					}elseif($arr['ChangeType'] == 'del_external_contact'){
    						$this->del_external_contact($arr);
    						Event::trigger('CustomerDelExternal',$arr);
    					}elseif($arr['ChangeType'] == 'del_follow_user'){
    						$this->del_follow_user($arr);
    						Event::trigger('CustomerDelFollow',$arr);
    					}
    				}elseif($arr['Event'] == 'change_external_chat'){
    					if($arr['ChangeType'] == 'create'){
    						$this->create_external_chat($arr);
    					}elseif($arr['ChangeType'] == 'update'){
    						$data = $this->change_external_chat($arr);
    						Event::trigger('ChangeExternalChat',$data);
    					}elseif ($arr['ChangeType'] == 'dismiss') {
    						$this->delete_external_chat($arr);
    					}
    				}
    			} else {
    				diy_log("解密失败ERR: " . $errCode . "\n\n");
    			}
			}
			echo "success";
		}
	}

	//添加企业客户事件
	private function addExternalContact($arr){
	    $this->import_et_dynamic(1,$arr);
		$CorpID = $arr['ToUserName'];//企业微信CorpID
		$qyConfig = $this->config;
		if(!$qyConfig){
			return;
		}
		$wid = $qyConfig["wid"];
		//获取客户详情 导入数据
		$customerInfoRes = QyWechatApi::getExternalDetail($wid,$arr['ExternalUserID']);
		if($customerInfoRes['errcode'] == 0){
			$staff = Helper::getUser(['wid'=>$wid,'userid'=>$arr['UserID']]);
			$customerInfo = $customerInfoRes;
			$qyCustomer = Helper::getCustomer(['wid'=>$wid,'staff_id'=>$staff['id'],'external_userid'=>$arr['ExternalUserID']]);
			$user = '';
			$tags = [];
			foreach($customerInfo['follow_user'] as $followuser){
				if($staff["userid"] == $followuser['userid']){
					$user = $followuser;
					foreach($followuser['tags'] as $ftag){
						$tags[] = $ftag['tag_id'];
					}
				}
			}
			$data["wid"] = $wid;
			$data["staff_id"] = $staff['id'];
			$data["external_userid"] = $customerInfo['external_contact']['external_userid'];
			$data['name'] = filterEmoji($customerInfo['external_contact']['name']);
			$data['avatar'] = $customerInfo['external_contact']['avatar'];
			$data['type'] = $customerInfo['external_contact']['type'];
			$data['gender'] = $customerInfo['external_contact']['gender'];
			if(array_key_exists("unionid",$customerInfo['external_contact']))$data['unionid'] = $customerInfo['external_contact']['unionid'];
			if(array_key_exists("position",$customerInfo['external_contact']))$data['position'] = $customerInfo['external_contact']['position'];
			if(array_key_exists("corp_name",$customerInfo['external_contact']))$data['corp_name'] = $customerInfo['external_contact']['corp_name'];
			if(array_key_exists("corp_full_name",$customerInfo['external_contact']))$data['corp_full_name'] = $customerInfo['external_contact']['corp_full_name'];
			if(array_key_exists("external_profile",$customerInfo['external_contact']))$data['external_profile'] = json_encode($customerInfo['external_contact']['external_profile'],320);
			$data['qyuser_id'] = $staff['id'];
			$data['remark'] = filterEmoji($user['remark']);
			$data['description'] = $user['description'];
			$data['createtime'] = $user['createtime'];
			$data['tags'] = json_encode($tags,320);
			if(array_key_exists("remark_corp_name",$user))$data['remark_corp_name'] = $user['remark_corp_name'];
			$data['remark_mobiles'] = json_encode($user['remark_mobiles'],320);
			$data['add_way'] = $user['add_way'];
			if(array_key_exists("oper_userid",$user))$data['oper_userid'] = $user['oper_userid'];
			if(array_key_exists("state",$user))$data['state'] = $user['state'];
			$data['status'] = 0;
			if($qyCustomer){
				$res = Db::table("kt_wework_customer")->where(["id"=>$qyCustomer["id"]])->save($data);
			}else{
			    $res = Db::table("kt_wework_customer")->insertGetId($data);
			}
		}
	}

	public function edit_external_contact($arr){
		$CorpID = $arr['ToUserName'];//企业微信CorpID
		$qyConfig = $this->config;
		if(!$qyConfig){
			return;
		}
		$wid = $qyConfig["wid"];
		//获取客户详情 导入数据
		$customerInfoRes = QyWechatApi::getExternalDetail($wid,$arr['ExternalUserID']);
		if($customerInfoRes['errcode'] == 0){
			$staff = Helper::getUser(['wid'=>$wid,'userid'=>$arr['UserID']]);
			$customerInfo = $customerInfoRes;
			$qyCustomer = Helper::getCustomer(['wid'=>$wid,'staff_id'=>$staff['id'],'external_userid'=>$arr['ExternalUserID']]);
			$user = '';
			$tags = [];
			foreach($customerInfo['follow_user'] as $followuser){
				if($staff["userid"] == $followuser['userid']){
					$user = $followuser;
					foreach($followuser['tags'] as $ftag){
						$tags[] = $ftag['tag_id'];
					}
				}
			}
			$data["wid"] = $wid;
			$data["staff_id"] = $staff['id'];
			$data["external_userid"] = $customerInfo['external_contact']['external_userid'];
			$data['name'] = filterEmoji($customerInfo['external_contact']['name']);
			$data['avatar'] = $customerInfo['external_contact']['avatar'];
			$data['type'] = $customerInfo['external_contact']['type'];
			$data['gender'] = $customerInfo['external_contact']['gender'];
			$data['unionid'] = $customerInfo['external_contact']['unionid'];
			if(array_key_exists("position",$arr))$data['position'] = $customerInfo['external_contact']['position'];
			if(array_key_exists("corp_name",$arr))$data['corp_name'] = $customerInfo['external_contact']['corp_name'];
			if(array_key_exists("corp_full_name",$arr))$data['corp_full_name'] = $customerInfo['external_contact']['corp_full_name'];
			if(array_key_exists("external_profile",$arr))$data['external_profile'] = json_encode($customerInfo['external_contact']['external_profile'],320);
			$data['qyuser_id'] = $staff['id'];
			$data['remark'] = filterEmoji($user['remark']);
			$data['description'] = $user['description'];
			$data['createtime'] = $user['createtime'];
			$data['tags'] = json_encode($tags,320);
			if(array_key_exists("remark_corp_name",$user))$data['remark_corp_name'] = $user['remark_corp_name'];
			$data['remark_mobiles'] = json_encode($user['remark_mobiles'],320);
			$data['add_way'] = $user['add_way'];
			if(array_key_exists("oper_userid",$user))$data['oper_userid'] = $user['oper_userid'];
			if(array_key_exists("state",$user))$data['state'] = $user['state'];
			$data['status'] = 0;
			$res = Db::table("kt_wework_customer")->where(["id"=>$qyCustomer["id"]])->save($data);
		}
	}

	public function del_external_contact($arr){
		$this->import_et_dynamic(2,$arr);
		$config = CallbackModel::getConfig($arr['ToUserName']);
		$staff = Helper::getUser(['wid'=>$config["wid"],'userid'=>$arr['UserID']]);
		$customer = CallbackModel::getCustomer($config["wid"],$staff["id"],$arr['ExternalUserID']);
		if(!$customer) return "";
		$customerSave = CallbackModel::customerSave($customer["id"],1);
	}

	public function del_follow_user($arr){
		$this->import_et_dynamic(3,$arr);
		$config = CallbackModel::getConfig($arr['ToUserName']);
		$staff = Helper::getUser(['wid'=>$config["wid"],'userid'=>$arr['UserID']]);
		$customer = CallbackModel::getCustomer($config["wid"],$staff["id"],$arr['ExternalUserID']);
		if(!$customer) return "";
		$customerSave = CallbackModel::customerSave($customer["id"],2);
	}

	public function import_et_dynamic($type,$arr){
		$CorpID = $arr['ToUserName'];//企业微信CorpID
		$config = CallbackModel::getConfig($CorpID);
		$dynamic = CallbackModel::dynamicSave($config["wid"],$type,$arr);
	}

	public function change_external_chat($arr){
		//企业微信CorpID
		$CorpID = $arr['ToUserName'];
		$config = Db::table("kt_wework_config")->where(['corp_id'=>$CorpID])->find();
		$wid = $config["wid"];
		$group_chat_info = QyWechatApi::getExternalGroupchatDetail($arr['ChatId'],$wid);
		if($group_chat_info['errcode'] == 0){
			$info = $group_chat_info['group_chat'];
			if($arr["UpdateDetail"] == "add_member"){
			    $members = array_column(Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$arr["ChatId"],"status"=>1])->field("userid")->select()->toArray(), "userid");
    			$users = array_column($info['member_list'],"userid");
    			$arr["group_user"] = $users[count($users)-1];
				foreach($info["member_list"] as $member){
					$data["wid"] = $wid;
					$data["chat_id"] = $arr['ChatId'];
					$data["userid"] = $member['userid'];
					$data["type"] = $member['type'];
					$data["join_time"] = $member['join_time'];
					$data["join_scene"] = $member['join_scene'];
					$data["group_nickname"] = $member['group_nickname'];
					$data["name"] = $member['name'];
					$data["status"] = 1;
					$data["invitor"] = json_encode($member['invitor'],320);
					if(array_key_exists("unionid",$member))$data["unionid"] = $member['unionid'];
					$is_members = Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$arr["ChatId"],"userid"=>$member['userid']])->find();
					if($is_members)Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$arr["ChatId"],"userid"=>$member['userid']])->save($data);
					if(!$is_members)Db::table("kt_wework_group_member")->insertGetId($data);
				}
			}else if($arr["UpdateDetail"] == "del_member"){
				$users = array_column($info['member_list'],"userid");
				$members = array_column(Db::table("kt_wework_group_member")->where(["wid"=>$wid,"chat_id"=>$arr["ChatId"],"status"=>1])->field("userid")->select()->toArray(), "userid");
				$user = array_diff($members,$users);
				$user = array_values($user);
				$arr["group_user"] = $user[0];
				Db::table("kt_wework_group_member")->where(["userid"=>$user[0],"chat_id"=>$arr["ChatId"],"wid"=>$wid])->update(["status"=>0,"lossing_time"=>time()]);
			}else if($arr["UpdateDetail"] == "change_name"){
				$name = $group_chat_info['group_chat']['name'];
				Db::table("kt_wework_group")->where(["chat_id"=>$arr["ChatId"]])->update(["name"=>$name]);
			}else if($arr["UpdateDetail"] == "change_notice"){
				$notice = $group_chat_info['group_chat']['notice'];
				Db::table("kt_wework_group")->where(["chat_id"=>$arr["ChatId"]])->update(["notice"=>json_encode($notice)]);
			}
		}
		return $arr;
	}

	//客户群创建
	public function create_external_chat($arr){
		$CorpID = $arr['ToUserName'];
		$config = Db::table("kt_wework_config")->where(['corp_id'=>$CorpID])->find();
		$wid = $config["wid"];
		$group_chat_info = QyWechatApi::getExternalGroupchatDetail($arr['ChatId'],$wid);
		Log::error($group_chat_info);
		$info = $group_chat_info['group_chat'];
		$staff = Db::table("kt_wework_staff")->where(['wid'=>$wid,'userid'=>$info['owner']])->find();
		$data["wid"] = $wid;
		$data["chat_id"] = $arr["ChatId"];
		$data["name"] = $info["name"]?:"默认群聊";
		$data["create_time"] = $info["create_time"];
		$data["owner"] = $info["owner"];
		$data["staff_id"] = $staff["id"];
        if(isset($info['notice']))$data['notice'] = json_encode($info['notice']);
		$data["is_dismissed"] = 0;
		$data["admin"] = json_encode($info["admin_list"],320);
		$group_id = Db::table("kt_wework_group")->insertGetId($data);
		Log::error($group_id);
		foreach($info["member_list"] as $member){
			$data["chat_id"] = $arr['ChatId'];
			$data["userid"] = $member['userid'];
			$data["type"] = $member['type'];
			$data["join_time"] = $member['join_time'];
			$data["join_scene"] = $member['join_scene'];
			$data["group_nickname"] = $member['group_nickname'];
			$data["name"] = $member['name'];
			$data["status"] = 1;
            if(isset($member["invitor"]))$data["invitor"] = $member["invitor"];
			Db::table("kt_wework_group_member")->insert($data);
		}
	}

	//客户群删除事件
  	public function delete_external_chat($arr){
	  	Db::table("kt_wework_group")->where(["chat_id"=>$arr["ChatId"]])->update(["is_dismissed"=>1]);
  	}
}